package util;


import util.parser.BinaryTree;

import java.util.Collections;
import java.util.List;
import java.util.Vector;


public class RandomGameHandler implements GameHandler {
    private static final int MAX_COUNT = 50;
    private GameHandler nextHandler;

    @Override
    public void handleRequest() {

        if (!solve() && nextHandler != null) {
            nextHandler.handleRequest();
        }

    }

    @Override
    public void setNextHandler(GameHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    @Override
    public boolean solve() {

        for (int x = 0; x < 4; x++)
            for (int y = 0; y < 4; y++)
                for (int z = 0; z < 4; z++) {
                    List<String> exp = new Vector<>();
                    exp.add(OPERATORS[x]);
                    exp.add(OPERATORS[y]);
                    exp.add(OPERATORS[z]);
                    for (int i = 0; i < 4; i++) exp.add(Game.getInstance().getDigitAt(i).toString());

                    for (int i = 0; i < MAX_COUNT; i++) {
                        Collections.shuffle(exp);
                        if (Math.abs(Evaluator.eval(exp) - TARGET) < EPS) {
                            BinaryTree binaryTree = BinaryTree.createBinaryTree(exp);
                            StringBuffer buffer = new StringBuffer();
                            binaryTree.midVisit(buffer);

                            Game.getInstance().getSolution().add(buffer.toString());

                        }
                    }
                }
        return Game.getInstance().getSolution().isEmpty();
    }


}
